package main

import (
	"encoding/binary"
	"fmt"
	"time"

	"gitee.com/cjianwen/go/socks/v2"
)

type UserData struct {
	Tokent int
	Name   string
	Id     int
}

type PackData = socks.DefPackData
type ConnClient = socks.ConnClient[PackData, UserData]

func procPack(conn *ConnClient, pack *PackData) {

	fmt.Printf("recev: sockid = %d, cmd = %d, msg = %s \n", conn.GetId(), pack.Head.Cmd, string(pack.Data))

	cmd := pack.Head.Cmd
	switch cmd {
	case 1:
		conn.SendPack(socks.NewDefPackWithData(cmd, []byte("are you ok?")))

	case 2:
		conn.SendPackToQueue(socks.NewDefPackWithData(cmd, []byte("SendPackToQueue are you ok2?")))

	case 3:
		conn.SendPack(socks.NewDefPackWithData(cmd, []byte("are you ok3?")))
	default:
		conn.SendPackToQueue(socks.NewDefPackWithData(cmd, []byte("SendPackToQueue 你发了个啥?")))
		fmt.Printf("未知的协议: %d \n", cmd)
	}

}

func main() {
	msgReceiver := socks.NewMsgReceiver(socks.NewDefPackHelper(binary.LittleEndian), UserData{}, binary.LittleEndian)

	msgReceiver.OnConnect = func(conn *socks.ConnClient[socks.DefPackData, UserData]) {
		fmt.Println("msgReceiver.OnConnect")
	}

	msgReceiver.OnDisconnect = func(conn *socks.ConnClient[socks.DefPackData, UserData]) {
		fmt.Println("msgReceiver.OnDisconnect")
	}

	// msgReceiver.OnReadPack = func(conn *socks.ConnClient[socks.DefPackData, UserData], pack *socks.DefPackData) {
	// 	fmt.Println("msgReceiver.OnReadPack")
	// }

	err := msgReceiver.ListenAndServe(6688)

	if err != nil {
		fmt.Println("open socket error: ", err)
	} else {
		fmt.Println("server is listen: 6688:")
	}

	for {
		msgReceiver.HandlePacks(procPack)
		time.Sleep(time.Millisecond * 10)
	}
}
